package com.l024.loanthief.utils;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.core.content.FileProvider;
import androidx.core.os.EnvironmentCompat;
import androidx.fragment.app.FragmentActivity;

import com.l024.loanthief.help.AppHelp;
import com.tbruyelle.rxpermissions3.Permission;
import com.tbruyelle.rxpermissions3.RxPermissions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import io.reactivex.rxjava3.functions.Consumer;

/**
 * @author wu_ming_zhi_bei
 * @date 2021/1/20 15:26
 * @Notes
 */
public class CameraUtil {
    private static CameraUtil cameraUtil;
    private static final String[] permissionsGroup=new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};

    // 拍照的requestCode
    public static final int CAMERA_REQUEST_CODE = 1000;

    // 申请相机权限的requestCode
    public static final int PERMISSION_CAMERA_REQUEST_CODE = 1001;

    /**
     * 用于保存拍照图片的uri
     */
    private Uri mCameraUri;
    /**
     * 用于保存图片的文件路径，Android 10以下使用图片路径访问图片
     */
    private String mCameraImagePath;

    /**
     *  是否是Android 10以上手机
     */
    private boolean isAndroidQ = Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q;

    private CameraUtil(){}

    public static CameraUtil getInstance(){
        if(cameraUtil==null){
            synchronized (CameraUtil.class){
                if(cameraUtil==null){
                    cameraUtil = new CameraUtil();
                }
            }
        }
        return cameraUtil;
    }

    /**
     * 开启相机
     */
    private int count = 0;
    public void openCamera(FragmentActivity activity){
        RxPermissions rxPermissions = new RxPermissions(activity);
        rxPermissions.requestEach(permissionsGroup)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Throwable {
                        if(permission.granted){
                            count++;
                            //授权通过
                            if(count==permissionsGroup.length){
                                //开启相机
                                Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                // 判断是否有相机
                                if (captureIntent.resolveActivity(activity.getPackageManager()) != null) {
                                    File photoFile = null;
                                    Uri photoUri = null;
                                    if (isAndroidQ) {
                                        // 适配android 10
                                        photoUri = createImageUri();
                                    } else {
                                        try {
                                            photoFile = createImageFile();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }

                                        if (photoFile != null) {
                                            mCameraImagePath = photoFile.getAbsolutePath();
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                                //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri
                                                photoUri = FileProvider.getUriForFile(AppHelp.getInstance().getContext(), AppHelp.getInstance().getContext().getPackageName() + ".fileprovider", photoFile);
                                            } else {
                                                photoUri = Uri.fromFile(photoFile);
                                            }
                                        }
                                    }
                                    mCameraUri = photoUri;
                                    if (photoUri != null) {
                                        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                                        captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                                        activity.startActivityForResult(captureIntent, CAMERA_REQUEST_CODE);
                                    }
                                }
                            }
                        }else if(permission.shouldShowRequestPermissionRationale){
                            //拒绝但是没有电不提示
                            Toast.makeText(activity, "请授权", Toast.LENGTH_SHORT).show();
                        }else{
                            // 用户拒绝了该权限，而且选中『不再询问』那么下次启动时，就不会提示出来了
                            Toast.makeText(activity, "请到设置里面打开授权", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     *
     * @return 图片的uri
     */
    private Uri createImageUri() {
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return AppHelp.getInstance().getContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        } else {
            return AppHelp.getInstance().getContext().getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
        }
    }

    /**
     * 创建保存图片的文件
     * @return
     * @throws IOException
     */
    private File createImageFile() throws IOException {
        String imageName = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File storageDir = AppHelp.getInstance().getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        File tempFile = new File(storageDir, imageName);
        if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
            return null;
        }
        return tempFile;
    }

    /**
     * 设置图片
     * @param image
     */
    public void setImage(ImageView image){
        if (isAndroidQ) {
            // Android 10 使用图片uri加载
            image.setImageURI(mCameraUri);
        } else {
            // 使用图片路径加载
            image.setImageBitmap(BitmapFactory.decodeFile(mCameraImagePath));
        }
    }

    public String getImagePath(){
        if (isAndroidQ) {
            return getFilePathFromUri(AppHelp.getInstance().getContext(),mCameraUri);
        }else{
            return mCameraImagePath;
        }
    }


    public String getFilePathFromUri(Context context, Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns
                    .DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
}
